package com.example.demo.threadCommunication;

import lombok.SneakyThrows;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2020年07⽉21⽇<br/>
 * @version：v1.0.0<br>
 */
public class CyclicBarrierDemo2 {

    /**
     * 因为CyclicBarrier设置了拦截线程的数量是2，所以必须等代码中的第一个线程和线程A
     * 都执行完之后，才会继续执行主线程，然后输出2
     * <p>
     * CyclicBarrier可以用于多线程计算数据，最后合并计算结果的场景
     */
    private static CyclicBarrier c = new CyclicBarrier(2, new A());

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {

        Thread thread = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                System.out.println(1);
                c.await();
            }
        });

        thread.start();
        c.await();
        System.out.println(2);
    }

    static class A implements Runnable {

        @SneakyThrows
        @Override
        public void run() {
            System.out.println(3);
        }
    }

}
